package org.cy.websocket.stomp.server;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.lang.NonNull;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessageType;
import org.springframework.messaging.support.ChannelInterceptor;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.messaging.support.MessageHeaderAccessor;

import java.nio.charset.StandardCharsets;

/**
 * Created in 2021-05-13 16:51
 *
 * @author cao.yong
 */
public class StompOutboundChannel implements ChannelInterceptor {
    private static final Logger LOG = LoggerFactory.getLogger(StompOutboundChannel.class);
    @Override
    public Message<?> preSend(@NonNull Message<?> message, @NonNull MessageChannel channel) {
        SimpMessageHeaderAccessor accessor = SimpMessageHeaderAccessor.getAccessor(message, SimpMessageHeaderAccessor.class);
        SimpMessageType messageType = SimpMessageHeaderAccessor.getMessageType(message.getHeaders());
        if (SimpMessageType.CONNECT_ACK.equals(messageType)) {
            String result = "Client Connect Success!";
            byte[] payload = result.getBytes(StandardCharsets.UTF_8);
            return MessageBuilder.createMessage(payload, message.getHeaders());
        } else if (SimpMessageType.MESSAGE.equals(messageType)) {
            assert accessor != null;
            LOG.info("服务器发送消息到 {}", accessor.getDestination());
        }
        return message;
    }
}
